<template>
  <div class="login-page">
    <div class="login">
      <div class="header"><client-header :isInfo="false" /></div>
      <div class="login-item">
        <div class="loginInfo">
          <el-image style="width: 300px; height: 400px" :src="url" />
          <div class="login-panel">
            <h3 class="title">欢迎注册中酒云网</h3>
            <div class="login_type" @click="handleLoginChange">
              {{ loginType == "code" ? "短信登录" : "验证码登录" }}
            </div>
            <div class="register">
              没有账号? <a class="primColor" @click="handleRegister()">去注册</a>
            </div>
            <div>
              <el-form :model="accountForm" :rules="accountRules" :label-width="100" size="large" status-icon
                ref="formRef">
                <el-form-item label="用户名" v-if="loginType == 'code'" prop="userName">
                  <el-input v-model.trim="accountForm.userName" />
                </el-form-item>
                <el-form-item label="密码" v-if="loginType == 'code'" prop="password">
                  <el-input v-model.trim="accountForm.password" show-password />
                </el-form-item>
                <el-form-item label="验证码" v-if="loginType == 'code'" prop="code">
                  <el-input placeholder="输入验证码" v-model.trim="accountForm.code">
                    <template #append>
                      <div class="login_code" @click="refreshCode">
                        <Sidentify :identifyCode="identifyCode" />
                      </div>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="手机号" v-if="loginType == 'smsCode'" prop="phonenumber">
                  <el-input v-model.trim="accountForm.phonenumber" maxlength="11" />
                </el-form-item>
                <el-form-item label="短信验证码" v-if="loginType == 'smsCode'" prop="smsCode">
                  <el-input v-model.trim="accountForm.smsCode" placeholder="输入验证码">
                    <template #append>
                      <el-button @click="getSmsCode">{{ sendText }}</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="tips" v-if="loginType == 'smsCode'">
              <el-checkbox v-model="readAgreement" label="登录即视为您已阅读并同意 " size="large" />
              <i style="color: #4098ff; cursor: pointer" @click="handleAgreement">《服务条款》《隐私政策》</i>
            </div>
            <el-row justify="space-between" align="bottom" :gutter="20">
              <el-col :span="24">
                <el-button class="login-btn" type="primary" size="large" :loading="loading" @click="handleLogin()">
                  立即登录
                </el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
      <Agreement-modal v-model:show="agreementShow" type="USER_AGREEMENT" btn-text="确 定"
        @confirm="readAgreement = true" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted } from "vue";
import { getAssetURL } from "@/utils/load_assets";
import { localCache } from "@/utils/cache";
import ClientHeader from "@/components/client-header/client-header.vue";
import Sidentify from "@/components/Sidentify/Sidentify.vue";
import { ElForm, ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { codeLogin, login, getInfo, getRouter, settingList } from "@/api/loginApi";
import { sendLoginMsg } from "@/api/cloud/index";
import type { IAccount } from "@/types";
import isLogin from "@/utils/staic";
import { useRouter } from "vue-router";
import { encrypt, aesEncrypt } from '@/utils/jsencrypt'

const router = useRouter();

// 登录表单
const accountForm = reactive<IAccount>({
  userName: localCache.getCache("userName") ?? "",
  password: localCache.getCache("password") ?? "",
  code: "",
  phonenumber: "",
  smsCode: "",
});
const loading = ref(false); // 登录状态
const agreementShow = ref(false); // 协议弹窗
const readAgreement = ref(false); // 协议勾选
const loginType = ref("code"); // 登录方式
const sendText = ref("获取验证码");
const formRef = ref<InstanceType<typeof ElForm>>();
// 校验规则
const accountRules: FormRules = {
  userName: [
    { required: true, message: "必须输入帐号信息~", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度必须在2到20个字符之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "必须输入密码信息~", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{5,20}$/,
      message: "必须是5~20的数字或字母组成",
      trigger: "change",
    },
  ],
  code: [
    { required: true, message: "必须输入验证码信息~", trigger: "blur" },
    {
      pattern: /^\d{4}$/,
      message: "必须是4位的数字组成~",
      trigger: "change",
    },
    {
      validator: (rule, value) => {
        if (value != identifyCode.value) {
          refreshCode();
          return Promise.reject("验证码错误");
        }
        return Promise.resolve();
      },
      trigger: "blur",
    },
  ],
  phonenumber: [
    { required: true, message: "必须输入手机话", trigger: "blur" },
    {
      pattern: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/,
      message: "必须是正确的手机号格式",
      trigger: "change",
    },
  ],
  // smsCode: [{ required: true, message: "必须输入短信验证码", trigger: "blur" }],
};
//图形验证码
let identifyCodes = "1234567890";
let identifyCode = ref("");
const url = getAssetURL("login/leftCover.png"); // 个人注册
const isRemPwd = ref<boolean>(localCache.getCache("isRemPwd") ?? false); // 是否记住密码

onMounted(() => {
  refreshCode();
});

watch(isRemPwd, (val) => {
  localCache.setCache("isRemPwd", val);
});

// 随机验证码
const randomNum = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min) + min);
};

// 生成随机验证码
const makeCode = (o: string, l: number) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)];
  }
};

// 重置验证码
const refreshCode = () => {
  identifyCode.value = "";
  makeCode(identifyCodes, 4);
};

// 登录
const handleLogin = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (loginType.value == "smsCode" && !readAgreement.value) {
        ElMessage.warning("请先阅读并同意《服务条款》《隐私政策》");
        return;
      }
      loading.value = true;
      settingList({ key: "USER_LOGIN_STRATEGY" }).then(res => {

        let { strategy } = JSON.parse(res?.data.settingValue);
        let passList = { ...accountForm }
        if (loginType.value != "smsCode") {
          if (strategy == 'asymmetric') {
            passList.password = encrypt(passList.password)
          } else {
            passList.password = aesEncrypt(passList.password)
          }
        }
        let request = loginType.value == "smsCode" ? codeLogin : login;
        request(passList)
          .then((res: any) => {
            if (res.code == 200) {
              localCache.setCache("myToken", res.token);
              isLogin.value = res.token;
              localCache.setCache("loginState", 1);
              getUserInfo();
              getRouters();
              router.push("/client/home");
            }
          })
          .finally(() => {
            loading.value = false;
            refreshCode();
          });
      })

    }
  });
};

//  获取用户信息
const getUserInfo = () => {
  getInfo({}).then((res) => {
    localCache.setCache("myInformationAll", res);
  });
};

//  获取路由信息
const getRouters = () => {
  getRouter({}).then((res) => {
    localCache.setCache("Routers", res);
  });
};

// 切换登录方式
const handleLoginChange = () => {
  loginType.value = loginType.value == "code" ? "smsCode" : "code";
};

//获取验证码
const getSmsCode = () => {
  if (accountForm.phonenumber == "") {
    ElMessage.error("请输入手机号！");
    return;
  }
  if (sendText.value != "获取验证码") {
    return;
  }
  sendLoginMsg({ phone: accountForm.phonenumber }).then((res: any) => {
    if (200 == res.code) {
      ElMessage.success("短信发送成功！");
      let count = 60;
      let timer = setInterval(() => {
        sendText.value = count + "秒后重新获取";
        count--;
        if (count == 0) {
          sendText.value = "获取验证码";
          clearInterval(timer);
        }
      }, 1000);
    }
  });
};

//去注册
const handleRegister = () => {
  router.push("/register");
};

// 打开协议弹窗
const handleAgreement = () => {
  agreementShow.value = true;
};
</script>

<style lang="less" scoped>
.login-page {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login {
  width: 100%;
  height: 100%;
  background: url("../../assets/img/login/bg2.png");

  .header {
    width: 100%;
    background: #fff;
    margin-bottom: 20px;
    padding-left: 80px;
    padding-right: 100px;
  }

  .login-item {
    height: calc(100% - 84px);
    width: 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;

    .loginInfo {
      display: flex;
      align-items: flex-end;
      transform: translate(50%);

      .login-panel {
        width: 416px;
        height: 400px;
        padding: 20px;
        background: rgba(255, 255, 255, 0.8);
        margin-top: 40px;

        .title {
          text-align: left;
          margin-bottom: 15px;
        }

        .login_type {
          position: absolute;
          right: 20px;
          top: 60px;
          color: #4098ff;

          &:hover {
            cursor: pointer;
          }
        }

        .register {
          margin-bottom: 20px;
          cursor: pointer;
        }

        .tips {
          margin: 20px 0;
          color: #b2b2b2;
        }

        .controls {
          display: flex;
          margin-top: 12px;
          justify-content: space-between;
        }

        .login-btn {
          margin-top: 10px;
          width: 100%;
        }

        .login_code {
          height: 38px;
        }
      }
    }
  }
}

:deep(.el-input-group__append) {
  padding: 0;
  overflow: hidden;
}
</style>
